package com.xiaoniu.douyinvideo.apps

import android.text.TextUtils
import android.widget.Toast
import com.blankj.utilcode.util.Utils
import com.xiaoniu.douyinvideo.util.LogUtil
import com.xiaoniu.douyinvideo.util.toast
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

/**
 * @author zhaohe
 * @date 2021/3/26 15:07
 * @desc 视频app
 */
abstract class VideoApp {
    /**
     * html链接
     *
     * @return
     */
    abstract fun htmlUrl(): String?

    /**
     * 视频地址转换
     *
     * @param videoUrl
     * @return
     */
    abstract fun videoUrlTransform(videoUrl: String?): String?

    /**
     * 解析出网页中的video url
     *
     * @param htmlCode
     * @return Pair<A, B>    A:视频原url B:视频重定向后的真实url
     */
    abstract fun parseHtml(htmlCode: String?): Pair<String, String>?

    /**
     * 获取重定向地址
     *
     * @param videoUrl 从html中获取的视频地址
     * @return 获取真实video url
     */
    fun getRealUrl(videoUrl: String?): String? {
        LogUtil.i("原始视频连接：" + videoUrl)
        var realUrl = videoUrl
        try {
            val url = URL(videoUrl)
            val conn = url.openConnection() as HttpURLConnection
            conn.setRequestProperty(
                "user-agent", "Mozilla/5.0.html (iPhone; U; CPU iPhone OS 4_3_3 like Mac " +
                        "OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) " +
                        "Version/5.0.html.2 Mobile/8J2 Safari/6533.18.5 "
            )
            conn.setInstanceFollowRedirects(false)
            val code = conn.getResponseCode()
            var redirectUrl: String? = ""
            if (302 == code) {
                redirectUrl = conn.getHeaderField("Location")
            }
            if (!TextUtils.isEmpty(redirectUrl)) {
                realUrl = redirectUrl
            }
            conn.disconnect()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return realUrl
    }

    fun showToast(msg: String?) {
        if (TextUtils.isEmpty(msg)) {
            return
        }
        MainScope().launch {
            msg?.toast()
        }
    }
}
